package com.lungle.warmdiary.app.view.testcampaign.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.MySwipeRefreshLayout;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseDetailFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Entity;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.event.CampaignGoToDetail;
import com.lungle.warmdiary.app.model.event.CampaignMessageEvent;
import com.lungle.warmdiary.app.model.event.CampaignMyEvent;
import com.lungle.warmdiary.app.model.event.CampaignStatueRefreshEvent;
import com.lungle.warmdiary.app.model.response.CampaignDetail;
import com.lungle.warmdiary.app.model.response.CampaignLink;
import com.lungle.warmdiary.app.model.response.CampaignMycomment;
import com.lungle.warmdiary.app.ui.dialog.CommonDialog;
import com.lungle.warmdiary.app.ui.empty.EmptyLayout;
import com.lungle.warmdiary.app.ui.horizontal.HorizontalScrollViewAdapter;
import com.lungle.warmdiary.app.ui.horizontal.MyHorizontalScrollView;
import com.lungle.warmdiary.app.utils.LogUtils;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.lungle.warmdiary.app.view.testcampaign.CampaignListTab;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPreview;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by zhangxueyuan on 16/9/29.
 * <p>
 * 亲测详情
 */
public class CampaignDetailFragment extends BaseDetailFragment implements View.OnClickListener {
    private static final String SCREEN = "campaign detail";

    public final static String BUNDLE_KEY_PAGE = "BUNDLE_KEY_PAGE";
    public final static String BUNDLE_KEY_ARGS = "BUNDLE_KEY_ARGS";
    private static final int CONTENT_MAX = 70;


    @Bind(R.id.campaign_icon)
    ImageView campaignIcon;
    @Bind(R.id.campaign_title)
    TextView campaignTitle;
    @Bind(R.id.campaign_vendor)
    TextView campaignVendor;
    @Bind(R.id.campaign_reward)
    TextView campaignReward;
    @Bind(R.id.campaign_status)
    TextView campaignStatus;
    @Bind(R.id.campaign_payment)
    TextView campaignPayment;
    @Bind(R.id.campaign_commentor)
    TextView campaignCommentor;
    @Bind(R.id.campaign_comment_content)
    TextView campaignCommentContent;
    @Bind(R.id.campaign_bt_all_commments)
    Button campaignBtAllCommments;
    @Bind(R.id.ll_comment_container)
    LinearLayout llCommentContainer;
    @Bind(R.id.id_gallery)
    LinearLayout idGallery;
    @Bind(R.id.campaign_content)
    TextView campaignContent;
    @Bind(R.id.sv_active_container)
    ScrollView svActiveContainer;
    @Bind(R.id.srl_refresh)
    MySwipeRefreshLayout srlRefresh;
    @Bind(R.id.error_layout)
    EmptyLayout errorLayout;
    @Bind(R.id.campaign_join)
    Button campaignJoin;

    @Bind(R.id.campaign_screen)
    MyHorizontalScrollView campaignScreen;


    @Bind(R.id.num1)
    TextView num1;
    @Bind(R.id.num2)
    TextView num2;


    private HorizontalScrollViewAdapter mAdapter;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_campaign_detail;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(getLayoutId(), container, false);
        ButterKnife.bind(this, view);
        initData();
        initViews(view);
        return view;
    }


    public void initViews(View view) {
    }

    @Override
    public void onResume() {
        super.onResume();
        if(onResumeRefresh){
            onResumeRefresh=false;
            LogUtils.printLogD("CampaignDetailFragment onResume ");
            sendRequestData();
        }
        MobclickAgent.onPageStart(SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(SCREEN);
        MobclickAgent.onPause(getActivity());

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private String campaignId;

    @Override
    public void initData() {
        campaignId = getActivity().getIntent().getStringExtra("campaignid");
    }


    @Override
    protected void sendRequestData() {
        ApiFactory.getUserApi().getCampaignDetail(campaignId).subscribeOn(Schedulers.io())
                .compose(this.<Result>bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(getSubscriber());
    }

    private CampaignDetail detail;

    @Override
    protected void executeOnLoadDataSuccess(Entity entity) {
        detail = (CampaignDetail) entity;
        CampaignMessageEvent campaignMessageEvent = new CampaignMessageEvent();
        campaignMessageEvent.setShareLinK(detail.getShortShareLink());
        campaignMessageEvent.setProduceId("" + detail.getProductid());
        campaignMessageEvent.setStatus(detail.getStatus());
        campaignMessageEvent.setShareLinkTitle(detail.getLinkText());
        EventBus.getDefault().post(campaignMessageEvent);

        fillUI();
    }


    private void fillUI() {
        ImageLoader loader = ImageLoader.getInstance();
        loader.displayImage(detail.getIcon(), campaignIcon);
        campaignTitle.setText(String.format("%s | %s", detail.getName(), detail.getBrief()));
        campaignVendor.setText(detail.getVendor());
        campaignReward.setText(String.format("%s%.2f元", "亲测奖金：", detail.getPrize()));
        campaignStatus.setText(CampaignListTab.getTabByStatus(detail.getStatus()).getTitle());
        campaignStatus.setTextColor(CampaignListTab.getTabByStatus(detail.getStatus()).color);

        campaignPayment.setText(getPaymentOnEffect(detail.getPrize(), detail.getAndroidConvertPrice(), detail.getIosConvertPrice(), detail.getIndividualLimit()));


        // TODO: 16/9/30  null的判断，注意
        if (detail.getProductReviews() != null && detail.getProductReviews().size() > 0) {
            llCommentContainer.setVisibility(View.VISIBLE);
            campaignCommentor.setText(detail.getProductReviews().get(0).getUser());
            String content = detail.getProductReviews().get(0).getContent();
            if (content.length() > CONTENT_MAX) {
                content = content.substring(0, CONTENT_MAX);
                campaignCommentContent.setText(String.format("%s...", content));
            } else {
                campaignCommentContent.setText(content);
            }

        } else {
            llCommentContainer.setVisibility(View.GONE);
        }

        campaignContent.setText(detail.getDesc());


//        if (detail.getProductTested() == 1) {
//            campaignJoin.setVisibility(View.GONE);
//        } else if (detail.getProductTested() == 0) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) srlRefresh.getLayoutParams();

        if (detail.getStatus() == CampaignDetail.CAMPAIGNEXECUTE) {
            campaignJoin.setVisibility(View.VISIBLE);
            campaignJoin.setText("参与亲测");
            layoutParams.bottomMargin = (int) getResources().getDimension(R.dimen.button_height_bottom);
            srlRefresh.setLayoutParams(layoutParams);
        } else if (detail.getStatus() == CampaignDetail.CAMPAIGNRECOMEND) {
            campaignJoin.setVisibility(View.VISIBLE);
            campaignJoin.setText("提交评价");
            layoutParams.bottomMargin = (int) getResources().getDimension(R.dimen.button_height_bottom);
            srlRefresh.setLayoutParams(layoutParams);
        } else {
            RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) srlRefresh.getLayoutParams();
            campaignJoin.setVisibility(View.GONE);
            layoutParams1.bottomMargin = 0;
            srlRefresh.setLayoutParams(layoutParams);

//            }
        }

        mAdapter = new HorizontalScrollViewAdapter(getActivity(), detail.getImages());
//        //添加滚动回调
//        campaignScreen
//                .setCurrentImageChangeListener(new MyHorizontalScrollView.CurrentImageChangeListener() {
//                    @Override
//                    public void onCurrentImgChanged(int position, View viewIndicator) {
//                    }
//                });
        //添加点击回调
        campaignScreen.setOnItemClickListener(new MyHorizontalScrollView.OnItemClickListener() {

            @Override
            public void onClick(View view, int position) {
                PhotoPreview.builder()
                        .setPhotos((ArrayList) detail.getImages())
                        .setCurrentItem(position)
                        .setShowDeleteButton(false)
                        .start(getActivity());
            }
        });
        //设置适配器
        campaignScreen.initDatas(mAdapter);

        if (detail.getReward2() == 0) {
            num1.setText(Html.fromHtml(String.format("<font color=#B5ABAA>未到余额：%.2f元</font>", detail.getReward2())));

        } else {
            num1.setText(Html.fromHtml(String.format("未到余额：<font color=#F57818>%.2f</font>元", detail.getReward2())));

        }

        if (detail.getReward1() == 0) {

            num2.setText(Html.fromHtml(String.format("<font color=#B5ABAA>已到余额：%.2f元</font>", detail.getReward1())));

        } else {

            num2.setText(Html.fromHtml(String.format("已到余额：<font color=#4EB122>%.2f</font>元", detail.getReward1())));
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.campaign_join, R.id.campaign_bt_all_commments})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.campaign_join:
                if (detail.getStatus() == CampaignDetail.CAMPAIGNEXECUTE) {

                    String message = "温馨提示：亲测仅适用于首次下载使用该应用.";

                    if (!TextUtils.isEmpty(detail.getConvertDesc())) {
                        String s = String.format("%s\n%s", message, detail.getConvertDesc());
                        message = s;
                    }
                    CommonDialog dialog = new CommonDialog(getActivity());
                    dialog.setMessageString(message);
                    dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            dialog.dismiss();
                            goApi();
                        }
                    });
                    dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    dialog.show();


                } else if (detail.getStatus() == CampaignDetail.CAMPAIGNRECOMEND) {

                    if (campaignMycomment != null) {
                        UIHelper.showCampaignComment(getActivity(), campaignMycomment, CampaignCommentFragment.UPDATE);

                    } else {

                        UIHelper.showCampaignComment(getActivity(), campaignId, "" + detail.getProductid(), null, CampaignCommentFragment.CREATE);
                    }
                }
                break;
            case R.id.campaign_bt_all_commments:
                EventBus.getDefault().post(new CampaignGoToDetail());
                break;

        }
    }


    private void goApi() {

        String link = detail.getShortLink();
        if (!TextUtils.isEmpty(link)) {
            UIHelper.openSysBrowser(getActivity(), link);
        } else {
            ApiFactory.getUserApi().getCampaignLink(campaignId).subscribeOn(Schedulers.io())
                    .compose(this.<Result<CampaignLink>>bindToLifecycle())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseSubscriber<Result<CampaignLink>>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                        }

                        @Override
                        public void onNext(Result<CampaignLink> result) {
                            UIHelper.openSysBrowser(getActivity(), result.getData().getLink());
                        }
                    });
        }

    }

    /**
     * 活动是否结束
     *
     * @return ture-end
     */

    //// TODO: 16/9/30 活动结束不能参与亲测，这个接口需要返回结束时间
    private boolean activeIsEnd() {
//        String endTime = Campaign.getEndtime();
//        if (!TextUtils.isEmpty(endTime)) {
//            try {
//                if (System.currentTimeMillis() + HttpHelper.getOffset() >= DateUtil.getDate(endTime)) {
//                    return true;
//                }
//            } catch (NumberFormatException e) {
//                LogUtils.printLogE(e.getMessage());
//            }
//        }
        return false;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


    }


    private Spanned getPaymentOnEffect(double every, double androidconvertPrice, double iosConvert, int individualLimit) {
        StringBuilder sb = new StringBuilder();
        sb.append(" 奖励说明：完成亲测您将获得<font color=#f94848>").append(every).append("</font>元奖励；");

        boolean oneConvert = false;

        if (androidconvertPrice == 0 || iosConvert == 0 || androidconvertPrice == iosConvert) {
            oneConvert = true;
        }

        if (oneConvert) {
            double price = (androidconvertPrice > 0) ? androidconvertPrice : iosConvert;
            sb.append("亲测后通过社交网络传播，每次有效转化您还能获得<font color=#f94848>").append(price).append("</font>元奖励");
        } else {
            // TODO: 16/9/30  文案是否修改？？？
            double min = androidconvertPrice;
            double max = iosConvert;
            if (androidconvertPrice > iosConvert) {
                min = iosConvert;
                max = androidconvertPrice;
            }
            sb.append("亲测后通过社交网络传播，每次有效转化您还能获得<font color=#f94848>").append(min).append("-").append(max).append("</font>元奖励");
        }
        if (individualLimit != 0) {
            sb.append("，最多获得<font color=#FFA51B>").append(individualLimit).append("</font>次奖励");
        }
        return Html.fromHtml(sb.toString());
    }

    boolean onResumeRefresh = false;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onStatueChanged(CampaignStatueRefreshEvent event) {
//        mMediaId = event.getId();
//        sendRequestData();

        onResumeRefresh=true;

    }

    private CampaignMycomment campaignMycomment;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMyComment(CampaignMyEvent event) {
        campaignMycomment = event.getCampaignMyEvent();
//
    }


}
